package com.redis.util;

import com.redis.entity.Concert;
import com.redis.entity.User;
import com.redis.mapper.ConcertMapper;
import com.redis.mapper.UserMapper;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author: Li
 * @Date: 2024/12/5 20:49
 * @Description:
 */

@Component
public class RedissonBlommerUtil {
    @Resource
    private ConcertMapper concertMapper;
    
    // 使用 RedissionClient
    @Resource
    private RedissonClient redissonClient;
    private RBloomFilter<Object> bloomFilter;
    
    @PostConstruct
    public void init() {
        // 获取mysql中 concert 表的数据
        List<Concert> concertList = concertMapper.getAllConcert();
        
        bloomFilter = redissonClient.getBloomFilter("ConcertList");
        // 初始化布隆过滤器的大小：预计要添加原始10000000L，误差率为3%
        bloomFilter.tryInit(10000000L, 0.03);
        
        // 将每一个 user 加入布隆过滤器
        for (Concert concert : concertList) {
            // 构造key
            String key = "concert:" + concert.getCid();
            // 将 key 加入布隆过滤器中
            bloomFilter.add(key);
        }
        System.out.println("白名单中的数据个数： " + bloomFilter.count());
    }
    
    // 检查布隆过滤器中是否存在某个用户
    public boolean checkBloomFilter(Integer id) {
        String key = "concert:" + id;
        return bloomFilter.contains(key);
    }
}


